﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Blam_Unity.Classes.Engine.Halo_AA.gameAssetLevel.maps.images
{
    static class readMapImageBLF
    {
        /// <summary>
        /// Get the length of the image in the BLF container
        /// </summary>
        /// <param name="mio">Mojos IO already declared</param>
        /// <returns></returns>
        public static int getJIFILength(MojosIO mio)
        {
            long totalLength = mio.StreamLength;

            return (int)totalLength - (0x44 + 0x10B);
        }

        /// <summary>
        /// Extract the JIFI (JPEG) image from the BLF container
        /// </summary>
        /// <param name="mio">Mojos IO already declared</param>
        /// <param name="imageLength">Length of the image to extract from the BLF container</param>
        /// <returns></returns>
        public static byte[] getJIFIImage(MojosIO mio, int imageLength)
        {
            mio.Position = 0x44;
            return mio.ReadBytes(imageLength);
        }
    }

    static class saveMapImageBLF
    {
        /// <summary>
        /// Inject a JPEG image back into a mapimage blf container
        /// </summary>
        /// <param name="mio">Mojos IO already declared</param>
        /// <param name="newImageArray"></param>
        /// <param name="blfSize"></param>
        /// <param name="filePath"></param>
        public static void injectBLFImage(MojosIO mio, byte[] newImageArray, int blfSize, string filePath)
        {
            int imageLengthBLF = newImageArray.Length + 20;
            int imageLengthJIFI = newImageArray.Length;

            byte[] blfHeader;
            byte[] eofFooter;

            mio.Position = 0x00;
            blfHeader = mio.ReadBytes(0x44);

            mio.Position = (blfSize - 0x10B);
            eofFooter = mio.ReadBytes(0x10B);

            mio.Close();

            File.Delete(filePath);
            File.Create(filePath, (blfHeader.Length + eofFooter.Length + newImageArray.Length));

            mio = new MojosIO(filePath, Endian.Big);

            mio.Position = 0x00;
            mio.Write(blfHeader);

            mio.Position = 0x36;
            mio.Write(imageLengthBLF);

            mio.Position = 0x44;
            mio.Write(newImageArray);

            mio.Position = 0x42;
            mio.Write(imageLengthJIFI);

            mio.Position = (0x44 + imageLengthBLF);
            mio.Write(eofFooter);
        }
    }
}
